﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FaultBackService.Shared;
using FaultBackService.BLL;

namespace FaultBackService.DataHelper
{
    /// <summary>
    /// 实时故障分析事务类，获取SCADA数据库时间，处理实时故障
    /// </summary>
    class RealTimeFaultTransaction
    {
        /// <summary>
        /// SCADA数据库时间,用以写日志
        /// </summary>
        DateTime _currentTimeOfSCADA;
        /// <summary>
        /// 一个周期的十分钟数据,按时间降序排列
        /// </summary>
        IList<Models.t_TurbDataGenericViewModel> _tenMeanList;
        /// <summary>
        /// 最新周期十分钟数据的风场平均值
        /// </summary>
        Models.TenMeanFarmData _farmMean;

        private object thisLock = new object();

        /// <summary>
        /// 获取数据库的当前时间
        /// </summary>
        /// <returns></returns>
        public DateTime GetCurrentTimeOfDB()
        {
            using (Models.SiteDataContext context = new Models.SiteDataContext())
            {
                return context.Database.SqlQuery<DateTime>("SELECT GETDATE();").Single();
            }
        }

        /// <summary>
        /// 读取最新的十分钟数据，获取_tenMeanList,_currentTimeOfScada,Global.LastTenMeanInfo
        /// </summary>
        /// <returns>当前数据刷新状态，已刷新返回Ture,未刷新返回False</returns>
        public bool ReadNormalTenMeanOfLastCycle(DateTime dataTime)
        {
            _tenMeanList = new t_TurbDataGeneric().GetViewList(dataTime);

            if (_tenMeanList == null || _tenMeanList.Count == 0)
            {
                new Log().DataIsEmpty2(dataTime.ToString("yyyy/MM/dd HH:mm"));
                return false;
            }
            else
            {
                //读取成功，写日志
                new Log().ReadSCADASuccess2(dataTime.ToString(), _tenMeanList == null ? 0 : _tenMeanList.Count);
                return true;
            }
        }


        /// <summary>
        /// 读取最新的十分钟数据，获取_tenMeanList,_currentTimeOfScada,Global.LastTenMeanInfo
        /// </summary>
        /// <returns>当前数据刷新状态，已刷新返回Ture,未刷新返回False</returns>
        //public bool ReadNormalTenMeanOfLastCycle()
        //{
        //    _tenMeanList = new t_TurbDataGeneric().GetLastList(out _currentTimeOfSCADA);   //赋值

        //    //赋值Global
        //    if (Global.LastTenMeanInfo2.TimeStamp == _tenMeanList[0].TStampOfMidPoint
        //        && Global.LastTenMeanInfo2.TurbineId == _tenMeanList[0].NodeID)
        //    {
        //        new Log().DataIsOut();
        //        return false;
        //    }
        //    else
        //    {
        //        Global.LastTenMeanInfo2.TimeStamp = _tenMeanList[0].TStampOfMidPoint;
        //        Global.LastTenMeanInfo2.TurbineId = _tenMeanList[0].NodeID;
        //        //读取成功，写日志
        //        new Log().ReadSCADASuccess(_currentTimeOfSCADA.ToString());
        //        return true;
        //    }

        //}

        /// <summary>
        /// 解析十分钟数据，写入TenMeanFarmData，TenMeanData,RealTimeFaultData
        /// </summary>
        public void ParseTenMeanData(DateTime dataTime)
        {
            if (_tenMeanList != null || _tenMeanList.Count != 0)
            {
                //向表TenMeanFarmData写入一条记录，返回标识,返回风场平均数
                _farmMean = WriteTenMeanFarmData(dataTime);

                if (_farmMean.TenMeanFarmDataId != 0)
                {
                    //向表TenMeanData中写入数据
                    WriteTenMeanData(_farmMean.TenMeanFarmDataId);

                    //故障分析，将复数故障写入表RealTimeFaultData
                    var faultCount = new RealTimeFaultHelper(_tenMeanList, _farmMean).WriteRealTimeFault();
                    new Log().WriteRealFault(faultCount);
                }
            }

        }



        /// <summary>
        /// 写入TenMeanFarmData，返回标识列，异常标识列返回0
        /// </summary>
        private Models.TenMeanFarmData WriteTenMeanFarmData(DateTime dataTime)
        {
            //获取有效数据，数据有效指风机有效且数据非Null
            int[] normalTurbIds = new Turbine().GetNormalIds();


            //风场平均值，用来平均的风机数计数器
            int gboxCount = 0;
            int genCount = 0;
            //平均值总计
            float gboxTotal = 0f;
            float genTotal = 0f;
            //提取有效数据，计算风场平均值
            foreach (var tenMeanData in _tenMeanList)
            {
                if (normalTurbIds.Contains(tenMeanData.NodeID))
                {
                    if (tenMeanData.GBoxDegC_Mean != null && tenMeanData.GBoxDegC_Mean != 0)
                    {
                        gboxCount++;
                        gboxTotal += tenMeanData.GBoxDegC_Mean.GetValueOrDefault();
                    }
                    if (tenMeanData.GenDegC_Mean != null && tenMeanData.GenDegC_Mean != 0)
                    {
                        genCount++;
                        genTotal += tenMeanData.GenDegC_Mean.GetValueOrDefault();
                    }
                }
            }

            //写入表TenMeanFarmData
            var farmMean = new Models.TenMeanFarmData(); 
            if (gboxCount != 0)
            {
                farmMean.GBoxDegC_Mean = gboxTotal / gboxCount;
            }
            if (genCount != 0)
            {
                farmMean.GenDegC_Mean = genTotal / genCount;
            }
            if (farmMean.GBoxDegC_Mean != null || farmMean.GenDegC_Mean != null)
            {
                farmMean.GBoxDegC_TurbineCount = gboxCount;
                farmMean.GenDegC_TurbineCount = genCount;
                farmMean.Time = dataTime;
                int FarmMeanId = new TenMeanFarmData().Add(farmMean);
                //写入日志
                new Log().WriteFarmMean(FarmMeanId);

                farmMean.TenMeanFarmDataId = FarmMeanId;
            }
            else
            {
                farmMean.TenMeanFarmDataId =  0;
            }
            return farmMean;
        }

        /// <summary>
        /// 写入TenMeanData，按时间顺序
        /// </summary>
        /// <param name="list"></param>
        private void WriteTenMeanData(int farmMeanId)
        {
            IList<Models.TenMeanData> tenMeanDataList = _tenMeanList
                .Reverse()
                .Select(d => new Models.TenMeanData()
                {
                    TimeStamp = d.TStampOfMidPoint,
                    TenMeanFarmDataId = farmMeanId,
                    TurbineId = d.NodeID,
                    TurbineName = null,
                    GBoxDegC_Mean = d.GBoxDegC_Mean,
                    GenDegC_Mean = d.GenDegC_Mean
                }).ToList();
            new TenMeanData().AddList(tenMeanDataList);
        }








        /// <summary>
        /// 计算平均值
        /// </summary>
        float GetMean(IList<float> list)
        {
            float total = 0f;
            foreach (var item in list)
            {
                total = total + item;
            }
            return total / list.Count();

        }

    }


    /// <summary>
    /// 传感器数据风场平均值
    /// </summary>
    //struct FarmMean
    //{

    //    public float? GBoxDegC { get; set; }
    //    public float? GenDegC { get; set; }
    //}
}
